package com.smart.sso.server.controller.admin;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smart.mvc.model.Pagination;
import com.smart.mvc.model.Result;
import com.smart.mvc.validator.Validator;
import com.smart.mvc.validator.annotation.ValidateParam;
import com.smart.sso.server.common.LoginUser;
import com.smart.sso.server.controller.common.BaseController;
import com.smart.sso.server.log.SystemControllerLog;
import com.smart.sso.server.model.Role;
import com.smart.sso.server.model.User;
import com.smart.sso.server.model.UserRole;
import com.smart.sso.server.service.RoleAppService;
import com.smart.sso.server.service.RolePermissionService;
import com.smart.sso.server.service.RoleService;
import com.smart.sso.server.service.UserRoleService;
import com.smart.sso.server.service.UserService;
import com.smart.sso.server.util.OperationUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author Joe
 */
@Api(tags = "角色管理")
@Controller
@RequestMapping("/admin/role")
public class RoleController extends BaseController {

	@Resource
	private RoleService roleService;
	
	@Resource
	private RoleAppService roleAppService;
	
	@Resource
	private UserRoleService userRoleService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private RolePermissionService rolePermissionService;

	@ApiOperation("初始页")
	@RequestMapping(method = RequestMethod.GET)
	public String execute(Model model) {
		return "/admin/role";
	}

	@ApiOperation("新增/修改页")
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	@SystemControllerLog(operationId = OperationUtils.operation_role_add ,description = "新增角色")
	public String edit(@ApiParam(value = "id") Integer id, Model model) {
		Role role;
		if (id == null) {
			role = new Role();
		}
		else {
			role = roleService.get(id);
		}
		model.addAttribute("role", role);
		return "/admin/roleEdit";
	}

	@ApiOperation("列表")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public @ResponseBody Result list(
			@ApiParam(value = "角色名")String name,
			@ApiParam(value = "开始页码", required = true) @ValidateParam({ Validator.NOT_BLANK }) Integer pageNo,
			@ApiParam(value = "显示条数", required = true) @ValidateParam({ Validator.NOT_BLANK }) Integer pageSize,
			HttpServletRequest request) {
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");
		List<UserRole> userRole = userRoleService.findByUserRoleId(loginUser.getUserId(), null);
		int roleId = userRole.get(0).getRoleId();
		int userId = userRole.get(0).getUserId();
		if(userId == 1) {
			Pagination<Role> pagination = new Pagination<>(pageNo , pageSize);
			List<Role> roles = roleService.findByAll(null , roleId);
			pagination.setList(roles);
			pagination.setRowCount(roles.size());
			return Result.createSuccessResult().setData(pagination);//所有角色对管理员可见
		}
		else
			return Result.createSuccessResult().setData(roleService.findPaginationByName(name, roleId ,new Pagination<Role>(pageNo, pageSize)));
	}

	@ApiOperation("启用/禁用")
	@RequestMapping(value = "/enable", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_role_enable , description = "启用角色")
	public @ResponseBody Result enable(
			@ApiParam(value = "ids", required = true) @ValidateParam({ Validator.NOT_BLANK }) String ids,
			@ApiParam(value = "是否启用", required = true) @ValidateParam({ Validator.NOT_BLANK }) Boolean isEnable) {
		roleService.enable(isEnable, getAjaxIds(ids));
		return Result.createSuccessResult();
	}

	@ApiOperation("新增/修改提交")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_role_edit , description = "修改角色")
	public @ResponseBody Result save(
			@ApiParam(value = "id") Integer id,
			@ApiParam(value = "角色名", required = true) @ValidateParam({ Validator.NOT_BLANK }) String name,
			@ApiParam(value = "排序", required = true) @ValidateParam({ Validator.NOT_BLANK }) Integer sort,
			@ApiParam(value = "描述") String description,
			@ApiParam(value = "是否启用", required = true) @ValidateParam({ Validator.NOT_BLANK }) Boolean isEnable,
			HttpServletRequest request) {
		Role role;
		if (id == null) {
			role = new Role();
		}
		else {
			role = roleService.get(id);
		}
		role.setName(name);
		role.setSort(sort);
		role.setDescription(description);
		role.setIsEnable(isEnable);
		
		LoginUser cUser = (LoginUser)request.getSession().getAttribute("CURRENT_USER");
		List<UserRole> userRole = userRoleService.findByUserRoleId(cUser.getUserId(), null);
		int curRoleId = userRole.get(0).getRoleId();
		role.setPid(curRoleId);
		
		roleService.save(role);
		return Result.createSuccessResult();
	}
	
	@ApiOperation("删除")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_role_delete ,description = "删除角色")
	public @ResponseBody Result delete(
			@ApiParam(value = "ids", required = true) @ValidateParam({ Validator.NOT_BLANK }) String ids) {
		List<Integer> idList = getAjaxIds(ids);
		for(int i =0 ; i< idList.size() ; i++) {
			if(idList.get(i) ==1) {
				idList.remove(i);
				return Result.createSuccessResult().setMessage("禁止删除管理员！");
			}
		}
		for(int j =0 ; j <idList.size() ; j++) {
			List<UserRole> userRoles = userRoleService.findByUserRoleId(null, idList.get(j));
			for(int k=0 ; k< userRoles.size() ; k++) {
				UserRole userRole = userRoles.get(k);
				User user = userService.get(userRole.getUserId());
				user.setIsEnable(false);
				userService.update(user);
			}
		}
		roleService.deleteById(getAjaxIds(ids));
		roleAppService.deleteByRoleIds(getAjaxIds(ids));
		userRoleService.deleteByRoleIds(getAjaxIds(ids));
		rolePermissionService.deleteByRoleIds(getAjaxIds(ids));
		return Result.createSuccessResult();
	}
}